package com.sync.platform.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.sync.platform.entity.ServerConfig;
import com.sync.platform.mapper.ServerConfigMapper;
import com.sync.platform.service.ServerConfigService;
import com.sync.platform.util.SSHUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Server configuration service implementation
 */
@Service
public class ServerConfigServiceImpl extends ServiceImpl<ServerConfigMapper, ServerConfig> implements ServerConfigService {

    private static final Logger logger = LoggerFactory.getLogger(ServerConfigServiceImpl.class);

    @Override
    public boolean testConnection(ServerConfig serverConfig) {
        Session session = null;
        try {
            // Create SSH session
            session = SSHUtil.createSession(
                    serverConfig.getHost(),
                    serverConfig.getPort(),
                    serverConfig.getUsername(),
                    serverConfig.getPassword(),
                    serverConfig.getPrivateKeyPath()
            );

            // Try to connect
            session.connect(5000); // 5 seconds timeout

            return session.isConnected();
        } catch (JSchException e) {
            logger.error("Test server connection failed: {}", e.getMessage(), e);
            return false;
        } finally {
            SSHUtil.closeSession(session);
        }
    }

    @Override
    public boolean updateStatus(Long id, Integer status) {
        return lambdaUpdate()
                .eq(ServerConfig::getId, id)
                .set(ServerConfig::getStatus, status)
                .update();
    }

    @Override
    public int countServers() {
        return (int) count();
    }
}
